﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using ChoViet.CMS.Components;
using ChoViet.CMS.Properties;
using ChoViet.CMS.ViewModels;
using ChoViet.Lib.Common;
using ChoViet.Lib.Mail;
using ChoViet.Model;
using MVCMessage;
using ChoViet.Lib.Helpers;
using ChoViet.Lib.Paging;
namespace ChoViet.CMS.Controllers
{
    public class ShopController : BaseController
    {
        #region Site

        #region Site: HttpGet Index
        [HttpGet]
        public ActionResult Index(string demanNam, string cateName, string cityName, string adAtributeName, string adAtributeValue, int? cusTypeId, int? page)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            if (page == null) page = 1;
            var param = new ShopIndexViewModel();
            try
            {
                param.Demand = !string.IsNullOrEmpty(demanNam) ? eDataContext.Demands.FirstOrDefault(e => e.ShortName == demanNam) : null;
                param.City = !string.IsNullOrEmpty(cityName) ? eDataContext.Cities.FirstOrDefault(e => e.ShortName == cityName) : null;
                param.Category = !string.IsNullOrEmpty(cateName) ? eDataContext.Categories.FirstOrDefault(e => e.ShortName == cateName) : null;
                param.AdAttribute = !string.IsNullOrEmpty(adAtributeName) ? eDataContext.AdAttributes.FirstOrDefault(e => e.ShortName == adAtributeName) : null;
                param.AdAttributeValue = !string.IsNullOrEmpty(adAtributeValue) ? eDataContext.AdAttributeValues.FirstOrDefault(e => e.ShortValue == adAtributeValue) : null;

                param.Keyword = "";
                param.CusType = cusTypeId != null ? cusTypeId.Value : 0;
                param.Shops = ShopManager.GetListShop(param.Demand != null ? param.Demand.ID : 0, 0, param.City != null ? param.City.ID : 0, 0, param.CusType,
                param.Category != null ? param.Category.ID : 0, param.Keyword, true, true, "VIPID", "ASC", page.Value, Convert.ToInt32(Settings.Default.ShopPageSize), 0);
                return View(param);
            }
            catch
            {
                eDataContext.Dispose();
                Messages.AddErrorMessage("Không load được dữ liệu!");
                return View(param);
            }
        }
        #endregion

        #region Site: Details
        public ActionResult Details(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new ShopDetailsViewModel();
            try
            {
                param.Demand = new Demand();
                //var currentPageComment = Request["page"] != null ? Convert.ToInt32(Request["page"]) : 0;
                param.Shop = eDataContext.Shops.FirstOrDefault(e => e.ID == id);
                param.Ads = eDataContext.ShopAdMaps.Where(e => e.ShopID == id).Select(e => e.Ad).ToList();
                param.Shop.nView = string.IsNullOrEmpty(param.Shop.nView.ToString()) ? 1 : param.Shop.nView + 1;
                param.AdAttribute = new AdAttribute();
                param.AdAttributeValue = new AdAttributeValue();
                eDataContext.SubmitChanges();
                return View(param);
            }
            catch
            {
                eDataContext.Dispose();
                Messages.ClearAllMessage();
                Messages.AddFlashMessage("Gian hàng này đã hết hạn đăng trên website!");
                return View(param);
            }
        }
        #endregion

        #endregion

        #region CMS

        #region HttpGet IndexCms
        [RoleHelper(Roles = RoleSystem.Shop)]
        public ActionResult IndexCms(int? page)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new ShopIndexCMSViewModel();
            try
            {
                if (page == null) page = 1;
                string order = UserState.getUserStateFromRequest("Shop.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("Shop.orderDir", "orderDir", "desc").ToString();
                param.CurentCateId = Convert.ToInt32(UserState.getUserStateFromRequest("Shop.CatID", "CatID", 0));
                param.CurentAreaId = Convert.ToInt32(UserState.getUserStateFromRequest("Shop.AreaID", "AreaID", 0));
                param.CurentCityId = Convert.ToInt32(UserState.getUserStateFromRequest("Shop.CityID", "CityID", 0));
                param.CurentDistrictId = Convert.ToInt32(UserState.getUserStateFromRequest("Shop.DistrictID", "DistrictID", 0));
                param.CurentPubStatusId = Convert.ToInt32(UserState.getUserStateFromRequest("Shop.PubStatusId", "PubStatusId", 0));
                param.CurentForcusId = Convert.ToInt32(UserState.getUserStateFromRequest("Shop.ForcusId", "ForcusId", 0));
                param.PubStatus = Utils.StringToDictionary(Settings.Default.PubStatus, ",");
                param.ForcusStatus = Utils.StringToDictionary(Settings.Default.ShopForcus, ",");

                param.Keyword = UserState.getUserStateFromRequest("Ad.Keyword", "Keyword", "").ToString();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("article.pageSize", "PageSize", Settings.Default.PageSize).ToString());
                param.Shops = eDataContext.Shops
                    .Where(a => (param.CurentCateId > 0 ? (a.Category.ParentCategory.ID == param.CurentCateId || a.CateID == param.CurentCateId) : true))
                    .Where(a => param.CurentAreaId > 0 ? a.City.AreaID == param.CurentAreaId || a.City.AreaID == param.CurentAreaId : true)
                    .Where(a => param.CurentCityId > 0 ? a.CityId == param.CurentCityId : true)
                    .Where(a => param.CurentDistrictId > 0 ? a.DistricID == param.CurentDistrictId : true)
                    .Where(a => param.CurentPubStatusId != null && param.CurentPubStatusId == 1 ? a.PubYN == true : true)
                    .Where(a => param.CurentPubStatusId != null && param.CurentPubStatusId == 2 ? (a.PubYN == false || a.PubYN == null) : true)
                    .Where(a => param.CurentForcusId != null && param.CurentForcusId == 1 ? a.FocusYN == true : true)
                    .Where(a => param.CurentForcusId != null && param.CurentForcusId == 2 ? (a.FocusYN== false || a.FocusYN == null) : true)
                    .Where(a => (string.IsNullOrEmpty(param.Keyword) ? true : (a.Name.ToLower().Contains(param.Keyword.ToLower()) || a.MobileContact.Contains(param.Keyword) || a.ID.ToString() == param.Keyword || a.EmailContact.Contains(param.Keyword))))
                    .OrderBy(string.Format("{0} {1}", order, orderDir))
                    .ToPagedList(page.Value - 1, pageSize);

                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(param.CurentCateId);
                param.Areas = eDataContext.Areas.ToList();
                param.Cities = eDataContext.Cities.Where(e => e.AreaID == param.CurentAreaId).ToList();
                param.Districts = eDataContext.Districts.Where(e => e.CityID == param.CurentCityId).ToList();


                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;
                return View(param);
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion
        
        #region HttpGet CreateCms
        [RoleHelper(Roles = RoleSystem.Shop)]
        public ActionResult CreateCms()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new ShopEditCmsViewModel();
            try
            {
                param.Cities = eDataContext.Cities.ToList();
                param.Districts = eDataContext.Districts.Where(e => e.City.ID == 13).ToList();
                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                param.Demands = eDataContext.Demands.ToList();
                return View(param);
            }
            catch { eDataContext.Dispose(); ViewData["MessageInfo"] = "Tổng hợp dữ liệu ban đầu gặp sự cố!"; return RedirectToAction("IndexCms","Home"); }
        }
        #endregion

        #region HttpPost CreateCms

        [HttpPost]
        [RoleHelper(Roles = RoleSystem.Shop)]
        [ValidateInput(false)]
        public ActionResult CreateCms(ShopEditCmsViewModel rdata)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
            eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
            try
            {
                rdata.Shop.OpenDate = Request["OpenD"] != null && Request["OpenD"].ToString() != string.Empty ? Utils.ParseDateTime(Request["OpenD"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : (DateTime?)null;
                rdata.Shop.CloseDate = Request["CloseD"] != null && Request["CloseD"].ToString() != string.Empty ? Utils.ParseDateTime(Request["CloseD"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : (DateTime?)null;
                //UpdateModel(rdata);
                rdata.Shop.CreatedDate = DateTime.Now;
                //rdata.Ad.ViewNumber = Utils.Random2Number();
                eDataContext.Shops.InsertOnSubmit(rdata.Shop);
                eDataContext.SubmitChanges();
                //Image display
                HttpPostedFileBase fileImage = Request.Files["ShopImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    rdata.Shop.LogoPath = Utils.ReduceImageSize("\\" + Settings.Default.ShopLogoPath,rdata.Shop.ID.ToString(), Convert.ToInt32(Settings.Default.ShopLogRedureSizePercent), fileImage);
                    eDataContext.SubmitChanges();
                }
                // Xử lý tags
                eDataContext.Transaction.Commit();
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
            Messages.AddFlashMessage("Tạo gian hàng thành công!");
            return RedirectToAction("IndexCms");
        }
        #endregion

        #region HttpGet EditCms
        [RoleHelper(Roles = RoleSystem.Shop)]
        public ActionResult EditCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new ShopEditCmsViewModel();
            try
            {
                param.Shop = eDataContext.Shops.FirstOrDefault(e => e.ID == id);
                if (param.Shop.UserID.HasValue)
                {
                    param.User = eDataContext.Users.FirstOrDefault(e => e.ID == param.Shop.UserID);
                    param.Ads = eDataContext.Ads.Where(e => e.UserID == param.Shop.UserID || e.EmailContact == param.User.Email).ToList();
                }
                param.Cities = eDataContext.Cities.ToList();
                param.Districts = eDataContext.Districts.Where(e => e.City.ID == 13).ToList();
                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                param.Demands = eDataContext.Demands.ToList();
                param.ListAdIDInShop = eDataContext.ShopAdMaps.Where(e => e.ShopID == id).Select(e => e.AdID).ToList();
                return View(param);
            }
            catch { eDataContext.Dispose(); ViewData["MessageInfo"] = "Tổng hợp dữ liệu ban đầu gặp sự cố!"; return RedirectToAction("IndexCms", "Home"); }
        }
        #endregion

        #region HttpPost EditCms

        [HttpPost]
        [RoleHelper(Roles = RoleSystem.Shop)]
        [ValidateInput(false)]
        public ActionResult EditCms(int id, ShopEditCmsViewModel rdata)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
            eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
            try
            {
                rdata.Shop = eDataContext.Shops.FirstOrDefault(e => e.ID == id);
                UpdateModel(rdata);
                rdata.Shop.OpenDate = Request["OpenD"] != null && Request["OpenD"].ToString() != string.Empty ? Utils.ParseDateTime(Request["OpenD"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : (DateTime?)null;
                rdata.Shop.CloseDate = Request["CloseD"] != null && Request["CloseD"].ToString() != string.Empty ? Utils.ParseDateTime(Request["CloseD"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : (DateTime?)null;
               
                //Image display
                HttpPostedFileBase fileImage = Request.Files["ShopImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    // Delete old image
                    if (!string.IsNullOrEmpty(rdata.Shop.LogoPath))
                    {
                        Uploads.DeleteFile(Settings.Default.AdminRootPath + rdata.Shop.LogoPath.Replace('/','\\'));
                    }
                    rdata.Shop.LogoPath = Utils.ReduceImageSize("\\" + Settings.Default.ShopLogoPath, rdata.Shop.ID.ToString(), Convert.ToInt32(Settings.Default.ShopLogRedureSizePercent), fileImage);
                }
                // Delete the old ad into shop
                var listoldmap = eDataContext.ShopAdMaps.Where(e => e.ShopID == id).ToList();
                if (listoldmap.Count() > 0) {
                    eDataContext.ShopAdMaps.DeleteAllOnSubmit(listoldmap);
                    eDataContext.SubmitChanges();
                }
                // Add the ad into shop
                var list = eDataContext.Ads.Where(e => e.UserID == rdata.Shop.UserID || e.EmailContact == rdata.Shop.User.Email).ToList();
                if (list.Count() > 0)
                {
                    foreach (var item in list)
                    {
                        var ischeck = Request["chk_" + item.ID] != null ? Convert.ToBoolean(Request["chk_" + item.ID]) : false;
                        if (ischeck)
                        {
                            var shopadmap = new ShopAdMap() { ShopID = rdata.Shop.ID, AdID = item.ID };
                            eDataContext.ShopAdMaps.InsertOnSubmit(shopadmap);
                        }
                    }
                }
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
            Messages.AddFlashMessage("Tạo gian hàng thành công!");
            return RedirectToAction("IndexCms");
        }
        #endregion

        #region HttpGet DetailsCms

        [RoleHelper(Roles = RoleSystem.Shop)]
        public ActionResult DetailsCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new ShopDetailsCmsViewModel();
            try
            {
                param.Shop = eDataContext.Shops.FirstOrDefault(e => e.ID == id);
                param.Ads = eDataContext.ShopAdMaps.Where(e => e.ShopID == id).Select(e => e.Ad).Distinct().ToList();
                return View(param);
            }
            catch (Exception exp)
            {
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion

        #endregion
    }
}
